// src/services/websocketService.js

class WebSocketService {
  constructor() {
    this.socket = null;
  }

  connect(url) {
    this.socket = new WebSocket(url);
    this.socket.onopen = this.onOpen;
    this.socket.onmessage = this.onMessage;
    this.socket.onerror = this.onError;
    this.socket.onclose = this.onClose;
  }

  onOpen = () => {
    console.log("WebSocket Connected");
  }

  onMessage = (event) => {
    const data = JSON.parse(event.data);
    console.log("Received data:", data);
    this.callback(data);
  }

  onError = (error) => {
    console.error("WebSocket Error:", error);
  }

  onClose = () => {
    console.log("WebSocket Disconnected");
    // Optionally try to reconnect or handle a clean shutdown
  }

  setCallback(callback) {
    this.callback = callback;
  }

  send(data) {
    if (this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(data));
    } else {
      console.error("WebSocket is not open.");
    }
  }

  disconnect() {
    if (this.socket) {
      this.socket.close();
    }
  }
}

export const websocketService = new WebSocketService();